

#include "imtPublic.h"
#include "imtLog.h"

#include <windows.h>

namespace iMate {

	bool StdSysOut::init()
	{
		mValid = true;

		if (mStdSysOutType == Sout_Console)
		{
			HANDLE  hOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
			if (INVALID_HANDLE_VALUE == hOutput || 0 == hOutput)
			{
				::AllocConsole();
			}
			else return true;
			hOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
			if (INVALID_HANDLE_VALUE == hOutput || 0 == hOutput)
			{
				return false;
			}
			mHandle = (void*)hOutput;
			return true;
		}

		const TCHAR* outNames[] = {TEXT("imt_console"), TEXT("imt_log.txt"), TEXT("imt_debuglog.txt"), TEXT("imt_error.txt")};

		mStdSysOutType = mStdSysOutType < Sout_Log ? Sout_Log : 
			(mStdSysOutType > Sout_Error ? Sout_Error : mStdSysOutType);

		OFSTRUCT fileInfo;
		fileInfo.cBytes = sizeof(fileInfo);
		HFILE  hOutput = ::OpenFile(outNames[mStdSysOutType], &fileInfo, OF_CREATE|OF_WRITE);
		if (hOutput == HFILE_ERROR) return false;

		mHandle = (void*)hOutput;
		return true;
	}
	void StdSysOut::close()
	{
		if (mStdSysOutType == Sout_Console)
		{
			if (INVALID_HANDLE_VALUE != mHandle && 0 != mHandle)
			{
				::FreeConsole();
			}
		}
		else if ((HFILE)mHandle != HFILE_ERROR)
		{
			::CloseHandle((HANDLE)mHandle);
		}
		mHandle = 0;
	}

	size_t StdSysOut::write(char* str, size_t count)
	{
		DWORD wn = 0;
		if (mStdSysOutType == Sout_Console)
		{
			if (INVALID_HANDLE_VALUE != mHandle && 0 != mHandle)
			{
				::WriteFile((HANDLE)mHandle, str, (DWORD)count, &wn, 0);
			}
		}
		else if ((HFILE)mHandle != HFILE_ERROR)
		{
			::WriteFile((HANDLE)mHandle, str, (DWORD)count, &wn, 0);
		}
		return wn;
	}
	size_t StdSysOut::write(wchar_t* wstr, size_t count)
	{
		return 0;
	}

}//iMate